package com.iretailer.report.analyze.device.eas;

import com.iretailer.report.analyze.commonUtil.ResponeResultType;
import com.iretailer.report.analyze.device.DeviceCommon;
import com.iretailer.report.analyze.device.eas.model.AlarmDto;
import com.iretailer.report.influxdb.model.EasAlarm;
import com.iretailer.report.influxdb.service.InfluxdbEasAlarmService;
import com.iretailer.report.influxdb.util.TableName;
import com.iretailer.report.model.Device;
import com.iretailer.report.model.MallBusinessTime;
import com.iretailer.report.service.BusinessTimeService;
import com.iretailer.report.service.DevicesService;
import com.iretailer.report.util.StringUtil;
import com.iretailer.report.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * @Auther: xjw
 * @Date: 2019/9/24 0024 13:10
 * @Description:
 */
@Component
public class EasInsert {
    private static final Logger log = LoggerFactory.getLogger(EasInsert.class);

    @Autowired
    private DevicesService devicesService;
    @Autowired
    private DeviceCommon deviceCommon;
    @Autowired
    private BusinessTimeService businessTimeService;
    @Autowired
    private InfluxdbEasAlarmService influxdbEasAlarmService;

    public ResponeResultType insertEasAlarm(AlarmDto alarmDto) {
        try {
            Device device = devicesService.selectByDeviceId(alarmDto.getDeviceName());
            if (device != null) {
                if (alarmDto.getTimeSeries() != null && alarmDto.getTimeSeries().size() > 0) {
                    MallBusinessTime mallBusinessTime = businessTimeService.filterBusinessTime(device.getMallId(), LocalDateTime.now());
                    ZoneId timezone = ZoneId.systemDefault();
                    if (StringUtil.notEmpty(mallBusinessTime.getTimeZone())) {
                        timezone = ZoneId.of(mallBusinessTime.getTimeZone());
                    }
                    LocalDateTime lastDataTime = null;

                    boolean status = alarmInsert(device.getId(), device.getDeviceId(), timezone, lastDataTime, alarmDto, mallBusinessTime.getStartTime(), mallBusinessTime.getEndTime());
                    if (status) {
                        deviceCommon.updateDevice(device, lastDataTime, "", alarmDto.getIpAddress(), alarmDto.getSerialNumber());
                        log.error("eas alarm is true | {}", alarmDto.getDeviceName());
                        return ResponeResultType.getOkRequest(ResponeResultType.CFLType.CLOSE);
                    }

                }
            } else {
                log.error("eas alarm not find device | {}", alarmDto.getDeviceName());
            }
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
        }
    }

    private boolean alarmInsert(Long id, String deviceId, ZoneId timezone, LocalDateTime lastDataTime, AlarmDto alarmDto, String startTime, String endTime) {
        List<EasAlarm> inserts = new ArrayList<>();
        List<EasAlarm> insertBusiness = new ArrayList<>();
        List<String> timeSeries = alarmDto.getTimeSeries();
        List<Integer> alarmTimes = alarmDto.getMetricsSeries().getAlarmTimes();
        if (timeSeries.size() == alarmTimes.size()) {
            for (int i = 0, len = timeSeries.size(); i < len; i++) {
                EasAlarm easAlarm = new EasAlarm();
                easAlarm.setZoneid(String.valueOf(id));
                ZonedDateTime easTime = ZonedDateTime.of(TimeUtil.parse_LocalDateTime(timeSeries.get(i)), ZoneId.of("Etc/GMT-0"));
                lastDataTime = easTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
                ZonedDateTime time = easTime.withZoneSameInstant(timezone);
                easAlarm.setTime(time);
                easAlarm.setAlarmTimes(alarmTimes.get(i));
                inserts.add(easAlarm);
                //判断是否在营业时间内
                if (deviceCommon.judgeBusinessTime(time, timezone, startTime, endTime)) {
                    insertBusiness.add(easAlarm);
                }
            }
        } else {
            log.error("alarm times size {} != meric series size {}", timeSeries.size(), alarmTimes.size());
            return false;
        }
        if (inserts.size() > 0) {
            influxdbEasAlarmService.insertEasAlarm(inserts, TableName.EasAlarm.EasAlarm);
        }
        if (insertBusiness.size() > 0) {
            influxdbEasAlarmService.insertEasAlarm(insertBusiness, TableName.EasAlarm.EasAlarm_B);
        }
        log.info("eas alarm success | {} | {} |size {}", deviceId, lastDataTime, timeSeries.size());
        return true;
    }

}
